#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：python_learning 
@File ：socket_sender_with_GUI_chat8.py
@IDE  ：PyCharm 
@Author ：李涵彬
@Date ：2024/3/1 17:09 
"""

import socket
import tkinter as tk


def send_packet(target_ip: str, target_port: int, packet_data: bytes):
    try:
        # 创建一个TCP socket对象
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            # 连接到目标IP和端口
            s.connect((target_ip, target_port))

            # 发送报文数据
            s.sendall(packet_data)

            print("Packet sent successfully!")
    except Exception as e:
        print("Error:", e)


def default_values():
    # 默认IP为本机IP
    ip_entry.insert(0, "127.0.0.1")

    # 默认端口为8888
    port_entry.insert(0, "8888")

    # 默认报文内容为"test"
    data_entry.insert(tk.END, "test")


# 创建主窗口
root = tk.Tk()
root.title("Socket Packet Sender")

# 创建IP地址输入框
ip_label = tk.Label(root, text="Target IP Address:")
ip_label.grid(row=0, column=0, padx=5, pady=5)
ip_entry = tk.Entry(root)
ip_entry.grid(row=0, column=1, padx=5, pady=5)

# 创建端口号输入框
port_label = tk.Label(root, text="Target Port:")
port_label.grid(row=1, column=0, padx=5, pady=5)
port_entry = tk.Entry(root)
port_entry.grid(row=1, column=1, padx=5, pady=5)

# 创建报文内容输入框
data_label = tk.Label(root, text="Packet Data:")
data_label.grid(row=2, column=0, padx=5, pady=5)
data_entry = tk.Text(root, height=5, width=30)
data_entry.grid(row=2, column=1, padx=5, pady=5)

# 创建发送按钮
send_button = tk.Button(
    root,
    text="Send Packet",
    command=lambda: send_packet(
        ip_entry.get(),
        int(port_entry.get()),
        data_entry.get("1.0", tk.END).encode("utf-8"),
    ),
)
send_button.grid(row=3, column=0, columnspan=2, padx=5, pady=5)

# 设置默认值
default_values()

# 运行主事件循环
root.mainloop()
